import Core.Basic
from Core.package import *




def Checkout_Has_Msedge_Process(_process_name:str="msedge.exe"):
    """检查是否存在指定名称的进程
        
        Args:
            _process_name (str): 进程名称
        
        Returns:
            bool: 如果存在指定名称的进程，则返回 True，否则返回 False
        
        Example:
            >>> CheckMsEdgeProcess('msedge.exe')
            True
        """
    _is_process_running = False
    for _proc in psutil.process_iter(['name']):
        if _proc.info['name'] == _process_name:
            _is_process_running = True
            break
    return _is_process_running


def Checkout_Debug_Mode_Activate() -> bool:
    """
    检查调试模式路径是否可用

    Returns:
        bool: 如果调试模式路径可用，则返回 True，否则返回 False

    Example:
        >>> MyEdge.CheckOutDebugModePath()
        True
    """
    url = "http://127.0.0.1:9652/json/version"
    try:
        response = requests.get(url=url)
        if response.status_code == 200:
            result = True
        else:
            result = False
    except Exception as e:
        print(f"请求调试模式路径时发生错误: {e}")
        result = False
    return result


def Close_All_Msedge_Process(_process_name: str="msedge.exe") -> bool:
    """
    关闭所有指定名称的进程

    Args:
        _process_name (str): 进程名称

    Returns:
        bool: 如果成功关闭所有指定名称的进程，则返回 True，否则返回 False

    Example:
        >>> MyEdge.CloseAllMsEdgeProcess('msedge.exe')
        True
    """
    success = True  # 初始化返回值
    for proc in psutil.process_iter(['pid', 'name']):
        if _process_name == proc.info['name']:
            try:
                proc.kill()  # 关闭进程
                print(f"Closed Microsoft Edge process with PID: {proc.info['pid']}")
            except Exception as e:
                print(f"Failed to close Microsoft Edge process with PID: {proc.info['pid']}. Error: {e}")
                success = False  # 如果关闭失败，设置返回值为 False
    return success

def Start_Debugmode_Browser():
    # 定义启动命令
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 --disable-extensions "http://127.0.0.1:9652/json/version"'
    
    # 启动新的进程
    subprocess.Popen(command, shell=True)

def Start_Debugmode_Browser_With_Extensions():
    # 定义启动命令
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 "http://127.0.0.1:9652/json/version""'
    
    # 启动新的进程
    subprocess.Popen(command, shell=True)






class Worker_Thread(QThread):
    thread_task_data = Signal(dict)
    def __init__(self, parent = None):
        super().__init__(parent)
        self.task_data = dict()
    
    def run(self):
        try:
            Start_Debugmode_Browser()

        except Exception as e:
            print(f"提示 : 员工线程任务发生错误!\n\
                    错误信息: {e}")
        finally:
            self.thread_task_data.emit(self.task_data)
        
        
        
        # 线程任务完成，会自动发送信号的,无需手动发送,手动发送可能会导致发送两遍信号.
        # self.finished.emit()
    def __delattr__(self, name):
        print(f"提示 : 子任务子线程运行结束!正在销毁资源 {self}")
        return super().__delattr__(name)
    

class Staff_Browser_Start_Browser_Not_Plugins(QObject):
    Start_Task = Signal()   # 任务开始信号,启动任务时,请发送此信号
    Task_Finish = Signal()   # 任务完成信号,任务结束时候,请发送此信号
    Current_Completion_Process = Signal(int)
    Emergency_Stop = Signal()  # 紧急停止信号
    OnlyRun = Signal()  # 仅运行信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Start_Task.connect(self.RunTask)
        
    @Slot(str)
    def slot_fun(self,text):
        print(f"我是槽函数,我是 {text}")

    # 设置员工属性
    def Set_Staff_Attribute(self,**kwargs):
        """设置员工对象的属性，用于后续任务执行
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        print(f"已设置属性: {kwargs.keys()}")

    def RunTask(self):

        # 获取需要操作的 主线程 窗口的 UI 对象
        # 使用 self.parent() 获取父对象
        self.parent_widget = self.parent()
        if self.parent_widget is None:
            print(f"提示 : 父对象为空!\n请将创建员工对象时,将父对象作为参数传入!")
            return
        # 获取 任务按钮 UI 控件对象
        self.task_button_object_name = "pushButton_start_browser_not_plugins"
        self.task_button : QPushButton = self.parent().findChild(QPushButton,self.task_button_object_name)
        if self.task_button is None:
            print(f"提示 : 程序无法找到 {self.task_button_object_name} 对应的按钮!")
            print(f"提示 : 子任务结束!")
            return



        # 创建子线程
        self.workerthread = Worker_Thread()



        # 绑定信号
        self.workerthread.finished.connect(lambda : QMessageBox.information(self.parent_widget,"提示","打开浏览器(无插件启动)任务完成!"))
        self.workerthread.finished.connect(lambda : self.Task_Finish.emit())    # 子线程运行结束代表该员工类的任务结束
        self.workerthread.finished.connect(lambda : self.workerthread.quit())   # 线程结束，销毁线程
        self.workerthread.finished.connect(lambda : self.deleteLater())
        self.workerthread.finished.connect(lambda : self.task_button.setEnabled(True))
        # self.workerthread.thread_task_data.connect(lambda task_data: print(task_data))


        # 启动子线程,开始执行任务
        self.task_button.setEnabled(False)
        self.workerthread.start()
        

        


















if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    # 编写 控制台 程序
    staff = Qt_Custom_Staff_Class(app)
    staff.RunTask()
    
    sys.exit(app.exec_())